<script setup>
import { ref } from 'vue'

const loading = ref(false)
const isProcessing = ref(false) // 添加处理标记，防止重复点击

// 添加返回主页的方法
const goToHome = () => {
  try {
    uni.switchTab({
      url: '/pages/index/index',
      success: () => {
        console.log('成功跳转到首页')
      },
      fail: (err) => {
        console.error('跳转到首页失败:', err)
        // 显示错误提示
        uni.showToast({
          title: '跳转失败，请重试',
          icon: 'none'
        })
      }
    })
  } catch (error) {
    console.error('跳转过程中发生错误:', error)
  }
}

// 处理微信登录
const handleLogin = async () => {
  // 如果正在处理中，直接返回
  if (isProcessing.value || loading.value) {
    return
  }
  
  isProcessing.value = true
  loading.value = true
  
  try {
    // 获取用户信息 - 直接调用，不使用setTimeout
    const userProfileRes = await new Promise((resolve, reject) => {
      uni.getUserProfile({
        desc: '用于完善用户资料',
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })

    // 获取登录凭证
    const loginRes = await new Promise((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })

    console.log('login success:', loginRes)
    const code = loginRes.code
    const userInfo = userProfileRes.userInfo
    
    // 调用后端登录接口
    uni.showLoading({
      title: '登录中...',
      mask: true
    })
    
    uni.request({
      url: 'http://localhost:9210/wechat/login',
      method: 'POST',
      data: {
        code: code,
        nickName: userInfo.nickName,
        avatar: userInfo.avatarUrl,
        sex: userInfo.gender === 1 ? '0' : (userInfo.gender === 2 ? '1' : '2'),
        userType: '00',
        status: '0',
        delFlag: '0'
      },
      success: (response) => {
        const res = response.data
        if (res.code === 200) {
          // 保存token和用户信息
          uni.setStorageSync('token', res.data.token)
          uni.setStorageSync('userInfo', res.data.userInfo)
          
          // 修改跳转逻辑，使用更简单的方式
          uni.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1500,
            success: () => {
              // 延迟执行跳转，等待Toast显示完成
              setTimeout(() => {
                // 尝试使用redirectTo跳转到首页
                uni.redirectTo({
                  url: '/pages/index/index',
                  success: () => {
                    console.log('成功跳转到首页')
                  },
                  fail: (err) => {
                    console.error('redirectTo失败:', err)
                    // 如果redirectTo失败，尝试使用reLaunch
                    uni.reLaunch({
                      url: '/pages/index/index',
                      fail: (e) => {
                        console.error('reLaunch也失败:', e)
                        // 如果reLaunch也失败，最后尝试switchTab
                        setTimeout(() => {
                          uni.switchTab({
                            url: '/pages/index/index'
                          })
                        }, 300)
                      }
                    })
                  }
                })
              }, 1500)
            }
          })
        } else {
          uni.showToast({
            title: res.msg || '登录失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('backend login fail:', err)
        uni.showToast({
          title: '登录失败，请重试',
          icon: 'none'
        })
      },
      complete: () => {
        uni.hideLoading()
      }
    })
  } catch (err) {
    console.error('login process error:', err)
    if (err.errMsg && err.errMsg.includes('getUserProfile:fail')) {
      uni.showToast({
        title: '请允许获取用户信息',
        icon: 'none'
      })
    } else {
      uni.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      })
    }
  } finally {
    loading.value = false
    // 延迟重置处理标记，防止快速点击
    setTimeout(() => {
      isProcessing.value = false
    }, 500)
  }
}

// 添加协议勾选状态
const isAgreed = ref(true)

// 切换协议勾选状态
const toggleAgreement = () => {
  isAgreed.value = !isAgreed.value
}
</script>

<template>
  <view class="container">
    <!-- 中间Logo区域 -->
    <view class="logo-container">
      <text class="logo-text">AI全屋设计</text>
    </view>
    
    <!-- 登录按钮移到底部 -->
    <view class="bottom-login-container">
      <button 
        class="login-btn"
        :loading="loading"
        :disabled="isProcessing"
        @click="handleLogin"
      >
        快捷登录
      </button>
      
      <!-- 协议区域移到登录按钮下方 -->
      <view class="agreement-container">
        <view class="checkbox" @click="toggleAgreement">
          <view class="checkbox-inner" :class="{'checked': isAgreed}">
            <text v-if="isAgreed" class="check-icon">✓</text>
          </view>
        </view>
        <view class="agreement-text">
          <text class="agreement-normal">勾选表示您已阅读并同意以下协议</text>
          <text class="agreement-link">《设牛AI隐私政策》</text>
          <text class="agreement-normal">和</text>
          <text class="agreement-link">《设牛AI服务使用协议》</text>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  position: relative;
  padding: 0 40rpx;
}

/* Logo区域样式 */
.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 200rpx;
  margin-bottom: 60rpx;
}

.logo-text {
  font-size: 80rpx;
  font-weight: bold;
  color: #333;
}

/* 底部登录按钮样式 */
.bottom-login-container {
  margin-top: auto;
  margin-bottom: 100rpx;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.login-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #333;
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 8rpx;
  text-align: center;
  margin-bottom: 30rpx;
}

/* 协议区域样式 */
.agreement-container {
  display: flex;
  align-items: flex-start;
  margin-top: 10rpx;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx;
  margin-top: 6rpx;
}

.checkbox-inner {
  width: 36rpx;
  height: 36rpx;
  border: 2rpx solid #999;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox-inner.checked {
  background-color: #333;
  border-color: #333;
}

.check-icon {
  color: #fff;
  font-size: 24rpx;
}

.agreement-text {
  flex: 1;
  font-size: 24rpx;
  line-height: 1.5;
}

.agreement-normal {
  color: #666;
}

.agreement-link {
  color: #333;
}
</style>